package com.example.shopp_2301.index

import android.content.Context
import android.os.Bundle
import android.os.Handler
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.example.base.entity.Roll
import com.example.base.mvvm.BaseFragment
import com.example.shopp_2301.R
import com.example.shopp_2301.adapter.GoodsAdapter
import com.example.shopp_2301.adapter.MenuAdapter
import com.example.shopp_2301.adapter.MenuMutAdapter
import com.example.shopp_2301.adapter.NewsAdapter
import com.example.shopp_2301.adapter.TypeAdapter
import com.example.shopp_2301.databinding.FragmentIndexBinding
import com.example.shopp_2301.utils.GlideUtils
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.youth.banner.BannerConfig
import com.youth.banner.loader.ImageLoader
import java.util.Timer
import java.util.TimerTask


class IndexFragment : BaseFragment<FragmentIndexBinding,IndexViewModel>() {
    val imgs = mutableListOf<String>()//存放轮播图图片
    //定义适配器
    lateinit var menuAdapter: MenuAdapter
    lateinit var menuMutAdapter: MenuMutAdapter//多布局
    lateinit var newsAdapter: NewsAdapter
    lateinit var typeAdapter: TypeAdapter
    lateinit var goodsAdapter: GoodsAdapter
    var type = 4//分类
    var page = 1//页面
    //实例化适配器
    //val menuAdapter1 by lazy { MenuAdapter() }
    //定时器
    lateinit var timer:Timer
    val handler = Handler()
    var count = 0//当前显示的新闻头条下标

    override fun initView() {
        viewModel.index()
        //实例化适配器
       /* menuAdapter = MenuAdapter()

        binding.rvMenu.adapter = menuAdapter//绑定适配器
        binding.rvMenu.layoutManager = GridLayoutManager(context,5)//设置布局样式*/
        menuMutAdapter = MenuMutAdapter()
        binding.rvMenu.adapter = menuMutAdapter//绑定适配器
        binding.rvMenu.layoutManager = GridLayoutManager(context,5)//设置布局样式
        //初始化
        newsAdapter = NewsAdapter()
        binding.rvNews.adapter = newsAdapter
        binding.rvNews.layoutManager = LinearLayoutManager(context)
        //开始定时器
        timer = Timer()
        timer.schedule(object :TimerTask(){
            override fun run() {
                handler.post {
                    binding.rvNews.scrollToPosition(count)
                    count++
                    if(count==newsAdapter.data.size){
                        count=0
                    }
                }
            }
        },0,2000)
        //初始化 分类
        typeAdapter = TypeAdapter()
        binding.rvType.adapter = typeAdapter
        binding.rvType.layoutManager = GridLayoutManager(context,4)
        //点击分类，实现背景变化---有商品数据后，商品数据发生变化
        typeAdapter.setOnItemClickListener { adapter, view, position ->
            page = 1//点击分类时注意，页码要修改成1 注意  type一定设为全局变量，方便后续刷新或加载时拿到正确的数据
            type = typeAdapter.data[position].type.toInt()
            typeAdapter.setType(type)
            viewModel.indexGoods(type,3,page)
        }

        //请求首页商品
        viewModel.indexGoods(type,3,page)
        goodsAdapter = GoodsAdapter()
        binding.rvGoods.adapter = goodsAdapter
        binding.rvGoods.layoutManager = GridLayoutManager(context,2)

        //刷新加载更多数据
        binding.smart.setOnRefreshLoadMoreListener(object:OnRefreshLoadMoreListener{
            override fun onRefresh(refreshLayout: RefreshLayout) {
                page=1
                viewModel.indexGoods(type,3,page)
                binding.smart.finishRefresh()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                page++
                viewModel.indexGoods(type,3,page)
                binding.smart.finishLoadMore()
            }
        })
        //点击搜索框，跳转到搜索页面
        binding.tvSearch.setOnClickListener {
            ARouter.getInstance().build("/app/SearchActivity").navigation()
        }
        goodsAdapter.setOnItemClickListener { adapter, view, position ->
            ARouter.getInstance().build("/app/XqActivity").withInt("goodsId",goodsAdapter.data[position].id).navigation()
        }
    }

    override fun initData() {
        viewModel.indexSuccess.observe(this){
            if(it.code==200){
                it.data.banner.forEach {
                    imgs.add(it.pic)
                }
                binding.banner.setImages(imgs)
                    .setImageLoader(object :ImageLoader(){
                        override fun displayImage(
                            context: Context?,
                            path: Any?,
                            imageView: ImageView?
                        ) {
                            if (context != null&&path!=null&&imageView!=null) {
                                GlideUtils.loadCornerImage(context,path.toString(),imageView,20)
                            }
                        }
                    })
                    .setDelayTime(2000)//轮播时长
                    .setBannerStyle(BannerConfig.NUM_INDICATOR)//修改轮播图指示器样式
                    .setOnBannerClickListener {
                        ToastUtils.showLong("点击了第$it 张图片")
                    }
                    .start()

                //显示菜单
                it.data.menus.forEachIndexed { index, menu ->
                    menu.type = index%2
                }
                menuMutAdapter.data.clear()
                menuMutAdapter.data.addAll(it.data.menus)
                menuMutAdapter.notifyDataSetChanged()
                //显示新闻头条
                newsAdapter.data.clear()
                newsAdapter.data.addAll(it.data.roll)
                newsAdapter.data.add(Roll(2,"这是新增的一条头条","",""))//因为后台数据只有一条，人为加一条
                newsAdapter.data.add(Roll(3,"最近有促销活动，快来购买","",""))//因为后台数据只有一条，人为加一条
                newsAdapter.notifyDataSetChanged()
                //显示分类
                typeAdapter.data.clear()
                typeAdapter.data.addAll(it.data.explosiveMoney)
                typeAdapter.notifyDataSetChanged()
            }
        }
        viewModel.goodsSuccess.observe(this){
            if(it.code==200){
                if(page==1){
                    goodsAdapter.data.clear()
                }
                goodsAdapter.data.addAll(it.data.list)
                goodsAdapter.notifyDataSetChanged()
                //优化用户体验，当加载到最后没有数据时，给出提示
                if(it.data.list.size==0){
                    ToastUtils.showLong("没有更多数据了")
                }
            }
        }
    }

    override fun getViewModel(): Class<IndexViewModel> {
        return IndexViewModel::class.java
    }

    override fun getLayout(): Int {
        return R.layout.fragment_index
    }

}